package com.ouroboroswiki.core.content.image;

import java.awt.Dimension;
import java.util.Map;

import com.ouroboroswiki.core.AbstractContentRepositoryProxy;
import com.ouroboroswiki.core.Content;
import com.ouroboroswiki.core.ContentException;
import com.ouroboroswiki.core.ContentPath;
import com.ouroboroswiki.core.Version;
import com.ouroboroswiki.core.VersionBuilder;

public class ScalingImageContentRepositoryProxy extends
		AbstractContentRepositoryProxy {
	
	private String prefix;
	private Map<?,?> hints;
	
	public ScalingImageContentRepositoryProxy( String prefix, Map<?,?> hints ) {
		this.prefix = prefix;
		this.hints = hints; 
	}
	

	@Override
	public Content getContent(Object principal, ContentPath path,
			Version version, Map<String, Object> properties)
			throws ContentException {
		String name = path.getName();
		// does the name look like scaling
		Dimension maxDimension;
		if( name.startsWith( this.prefix ) ) {
			String post = name.substring( this.prefix.length() );
			int index = post.indexOf( 'x' );
			if( index < 0 ) {
				maxDimension = null;				
			} else {
				String maxWidthString = post.substring( 0, index );
				String maxHeightString = post.substring( index+1 );
				try {
					int maxWidth = Integer.parseInt( maxWidthString );
					int maxHeight = Integer.parseInt( maxHeightString );
					maxDimension = new Dimension( maxWidth, maxHeight );
				} catch( NumberFormatException ex ) {				
					maxDimension = null;
				}
			}
		} else {
			maxDimension = null;
		}
		Content result;
		result = proxied.getContent(
				principal, 
				path, 
				version, 
				properties
		);
		if( maxDimension != null ) {
			ScalingImageContentProxy image;
			image = new ScalingImageContentProxy(
					result, 
					maxDimension,
					hints
			);
			result = image;
		}
		return result;
	}

	@Override
	public boolean exists(Object principal, ContentPath path)
			throws ContentException {
		return proxied.exists(principal, path);
	}

	@Override
	public Version buildVersion(Object principal, ContentPath path,
			String[] versionPath, VersionBuilder versionBuilder)
			throws ContentException {
		return proxied.buildVersion(principal, path, versionPath, versionBuilder);
	}

}
